/* *
 * 柱形图
 * 说明：能适应单指标、多指标的展示（考虑多指标时可以转变为堆叠图）
 *     data.datas = [
      {
        id: "aaa",
        name: "aaa",
        regioncode: "aaa",
        regionname: "aaa",
        datas: {
          sdata: [
            {
              name: "直接访问",
              type: "bar",
              barWidth: "60%",
              data: [10, 52, 200, 334, 390, 330, 220]
            }
          ],
          xAxis: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
        },
        lon: "116.92866163503169",
        lat: "39.830660058696104"
      },
      {
        id: "bbb",
        name: "bbb",
        regioncode: "bbb",
        regionname: "bbb",
        datas: {
          sdata: [
            {
              name: "直接访问",
              type: "bar",
              barWidth: "60%",
              data: [10, 52, 200, 334, 390, 330, 220]
            }
          ],
          xAxis: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
        },
        lon: "104.04",
        lat: "30.40"
      }
    ]
 *
 */
import icon from "../../css/images/marker-icon.png";
import iconShadow from "../../css/images/marker-shadow.png";
import echarts from 'echarts'; // echarts 文件引入
import sgisLayerBase from '../../sgis.layer.base';
import colorPicker from './echarts.colorpicker'; // 颜色初始化配置文件
import styleModify from './echarts.stylemodify'; // 样式修改，包括透明度设置，可见性，图层的ZIndex顺序设置文件
export default {
  activeMap: {},
  graph: ``, // 图形
  charts: [], // chartOption，echart图表配置项参数记录
  /**
   * 创建地柱形图专题图
   * @param {Object} map 地图对象
   * @param {Object} data 格式化好的数据
   *      {
   *        "id":"",  专题图的id
   *        "name":"",  专题图的名称
   *         showThumbnails:false,
   *        "datas":[{   数据
   *         "id":"",     每个点的echarts id
   *          "name":"",    每个点的echarts name
   *          "regioncode":"",    每个点对应的区划代码
   *          "regionname":"",     每个点对应的区划名称
   *          "datas":{"sdata":[],"xAxis":[]},   echarts对应的seris数据和x轴数据
   *          "lon":"",     坐标点Y
   *          "lat":"",     坐标点X
   *       },{}]
   *    }
   */
  createLayer(map, data) {
    if (!data || data === undefined) {
      return;
    }
    if (!data.datas || data.datas === undefined) {
      return;
    }
    this.activeMap = map;
    const barLayerInfo = {
      id: "",
      name: "",
      layer: {},
      type: "bar"
    };
    const DefaultIcon = L.icon({
      iconUrl: icon,
      shadowUrl: iconShadow
    });
    L.Marker.prototype.options.icon = DefaultIcon;
    let barMarkers = [];
    const barLayer = L.layerGroup();
    barLayer.setCustomColor = this.setCustomColor; // 换颜色
    barLayer.setOpacity = styleModify.setOpaticty; // 设置透明度
    barLayer.setVisible = styleModify.setVisible; // 设置透明度
    barLayer.setZIndexOffset = this.setZIndexOffset; // 设置调整图层顺序函数;函数
    barLayer.autoCalgraph = this.autoCalgraph; // 换颜色
    barMarkers = this.createMarker(data.datas);
    // 此处必须先把容器加到地图上才能加载图表
    barLayer._layers = barMarkers;
    barLayer.addTo(this.activeMap);
    styleModify.onZoom(this.activeMap, barMarkers); // 为markers绘图添加缩放监听改变z-Index;
    this.createCharts(barMarkers, data.datas);
    barLayer.charts = { ...this.charts
    }; // 记录图像
    barLayer.calSData = this.calSData; // 记录图像
    barLayerInfo.layerId = "bar_chart_" + data.id + "_" + new Date().getTime();
    // 设置容器初始ZINdex,为后面调整图层顺序功能 开始
    styleModify.setLayerOrder(styleModify.curZindex, barLayer._layers, barLayerInfo.layerId);
    styleModify.layerOrder[barLayerInfo.layerId] = styleModify.curZindex;
    styleModify.curZindex -= 1;
    // 设置容器初始ZINdex,为后面调整图层顺序功能 结束
    // 记录id
    barLayer.layerId = barLayerInfo.layerId;
    barLayerInfo.html = this.calgraph(barLayerInfo.layerId);
    // 记录id
    barLayerInfo.name = data.name;
    barLayerInfo.show = data.showThumbnails !== false;
    barLayerInfo.layer = barLayer;
    sgisLayerBase.setOverLayers(barLayerInfo);
    return barLayerInfo;
  },
  /**
   * 创建echarts容器
   * @param {Objects[]} datas
   */
  createMarker(datas) {
    const resultMarkers = [];
    for (let i = 0, len = datas.length; i < len; i++) {
      const data = datas[i];
      // 初始化最小宽高开始
      let width = colorPicker.size;
      if (data.hasOwnProperty('width')) {
        width = data.width.slice(0, -2);
        width = parseInt(width);
        if (width < colorPicker.size) {
          width = colorPicker.size;
        }
      }
      let height = colorPicker.size;
      if (data.hasOwnProperty('height')) {
        height = data.width.slice(0, -2);
        height = parseInt(height);
        if (height < colorPicker.size) {
          height = colorPicker.size;
        }
      }
      // 初始化最小宽高结束
      const chartMarker = L.marker([data.lat, data.lon], {
        id: "bar_chart_" + data.id,
        pane: styleModify.pane, // 为设置自定义的图层顺序特别设定
        icon: L.divIcon({
          className: "leaflet-echart-icon",
          zIndex: 450,
          iconSize: [width, height],
          html: `<div id="bar_chart_${data.id}" style="width:${width}px;height:${height}px;position:relative;background-color:transparent;z-index:${styleModify.bar}"></div>`
        })
      });
      resultMarkers.push(chartMarker);
    }

    return resultMarkers;
  },
  /**
   * 创建图表
   * @param {Object} barMarkers 图表容器
   * @param {Object} datas 数据
   */
  createCharts(barMarkers, datas) {
    this.graph = [];
    if (!barMarkers || barMarkers === undefined) return;
    for (let i = 0; i < barMarkers.length; i++) {
      const chartMarkerId = barMarkers[i].options.id;
      const chart = echarts.init(document.getElementById(chartMarkerId));
      const data = datas[i];
      this.graph = [];
      const chartOption = {
        color: colorPicker.color,
        tooltip: {},
        toolbox: {
          show: true,
          itemSize: "10",
          bottom: "70%",
          feature: {
            magicType: {
              show: true,
              type: ["stack"]
            },
            restore: {
              show: true
            }
            // saveAsImage: {
            //   show: true
            // }
          }
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true
        },
        xAxis: [{
          type: "category",
          data: data.datas.xAxis, // 设置x轴坐标
          axisTick: {
            alignWithLabel: true
          },
          axisLabel: {
            color: colorPicker.bar.axisColor
          },
          axisLine: {
            show: true,
            lineStyle: {
              color: colorPicker.bar.axisColor
            }
          }
        }],
        yAxis: [{
          type: "value",
          splitLine: {
            show: false // 网格线不显示
          },
          axisLabel: {
            color: colorPicker.bar.axisColor
          },
          axisLine: {
            show: true,
            lineStyle: {
              color: colorPicker.bar.axisColor
            }
          }
        }],
        series: this.calSData(data.datas.sdata)
      };
      this.charts.push({
        id: barMarkers[i].options.id,
        echart: chart
      });
      chart.setOption(chartOption);
    }
  },
  /**
   *
   * @param {object} par{
     barStyle: [this.color1, "pink"],
     axisStyle: this.color1,
     axisLableStyle: this.color1
   }
   */
  setCustomColor(layers, pars) {
    const par = {
      ...pars,
      barStyle: pars.colors
    };
    for (const key in layers.charts) {
      this.graph = [];
      const item = layers.charts[key];
      const option = item.echart.getOption();
      // 设置x轴与y轴颜色 开始
      if (par.hasOwnProperty('axisStyle')) {
        option.xAxis = {
          ...option.xAxis,
          axisLine: {
            show: true,
            lineStyle: {
              color: par.axisStyle
            }
          }
        };
        option.yAxis = {
          ...option.yAxis,
          axisLine: {
            show: true,
            lineStyle: {
              color: par.axisStyle
            }
          }
        };
      }
      // 设置x轴与y轴颜色 结束
      // 设置x轴与y轴文字颜色开始
      try {
        if (par.hasOwnProperty('axisLableStyle')) {
          option.xAxis = {
            ...option.xAxis,
            axisLabel: {
              color: par.axisLableStyle
            }
          };
          option.yAxis = {
            ...option.yAxis,
            axisLabel: {
              color: par.axisLableStyle
            }
          };
        }
      } catch (err) {}
      // 设置x轴与y轴文字颜色结束
      // 设置柱状颜色
      let data = option.series;
      try {
        if (par.hasOwnProperty('barStyle')) {
          data = layers.calSData(data, par.barStyle);
        }
      } catch (err) {}
      option.series = data;
      item.echart.setOption(option);
    }
    // 变化图例组件
    layers.autoCalgraph(layers.layerId);
  }, // 自定义柱状颜色时使用该函数
  /* *格式化数据
   * @params data 传入数据
   * @param {array} customColor
   */
  calSData(data, customColor) {
    for (const key in data) {
      let index, indexc;
      try {
        index = key % colorPicker.color.length;
        indexc = key % customColor.length;
      } catch (err) {
        index = 0;
        indexc = 0;
      }
      data[key] = {
        ...data[key],
        itemStyle: {
          barBorderRadius: [50, 50, 0, 0],
          color: customColor && customColor[indexc] ? customColor[indexc] : data[key].color ? data[key].color : colorPicker.color[index]
        }
      };
      // 图例颜色自定义
      this.graph.push({
        name: data[key].name,
        color: data[key].itemStyle.color
      });
    }
    return data;
  },
  /**
   * 格式化数据
   * @param {*} layerId 图层id
   */
  // 图例计算颜色 开始
  calgraph(layerId) {
    let html = `<div style="padding:10px" class="${layerId}">`;
    for (const key in this.graph) {
      html += `<div>
        <div style='display:inline-block;width:40px;height:10px;background:${this.graph[key].color};margin:0;padding:0;border-radius:50px;'></div>
        <div style='display:inline-block;margin:0;padding:0;padding-left:10px;line-height:30px;'>${this.graph[key].name}</div>
      </div>`;
    }
    html += '</div>';
    return html;
  },
  /**
   *格式化数据
   * @param {*} layerId 图层id
   */
  autoCalgraph(layerId) {
    let html = `<div style="padding:10px" id="${layerId}">`;
    for (const key in this.graph) {
      html += `<div>
        <div style='display:inline-block;width:40px;height:10px;background:${this.graph[key].color};margin:0;padding:0;border-radius:50px;'> </div>
        <div style='display:inline-block;;margin:0;padding:0;padding-left:10px;line-height:30px;'>${this.graph[key].name}</div>
      </div>`;
    }
    html += '</div>';
    const layers = sgisLayerBase.overLayers;
    for (const key in layers) {
      if (layers[key].layerId === layerId) {
        layers[key].html = html;
      }
    }
    // sgisLayerBase.layerControlChange();
  },
  // 图例计算颜色 结束
  /** 设置调整图层顺序函数*/
  setZIndexOffset(index) {
    styleModify.setZIndexOffset(index, this.layerId, this._layers);
  }
};
